package org.layuiframework.stereotype.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.layuiframework.stereotype.vo.ResultVo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常处理(权限拒绝、登录失效等)
 * 如果用户认证或授权过程中出现错误,需要将其重定向到authenticationentrypoint并进行相应的错误处理。
 */
@Component
@ConditionalOnMissingBean(AuthenticationEntryPoint.class)
public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        ResultVo responseEntity = new ResultVo(401, "请先登录", null);
        httpServletResponse.setStatus(401);
        ObjectMapper mapper=new ObjectMapper();
//        if ("XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With")))
//            httpServletResponse.setStatus(401);
        httpServletResponse.getWriter().write(mapper.writeValueAsString(responseEntity));
    }
}
